package net.apexes.commons.guice.tx;

import java.sql.SQLException;

/**
 * 启用数据库事务<br/>
 * <br/>
 * 注意事项：<br/>
 * <ul>
 * <li>不支持事务嵌套，被嵌套调用的方法上将被忽略</li>
 * <li>在产生作用的代码区段中如果需要调用多个数据源，必须指定要开启事务的数据源名称，不支持同一作用代码区段有多个数据源开启事务</li>
 * </ul>
 *
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 */
public interface Txn extends AutoCloseable {

    static boolean isWithinTx() {
        return TxnImpl.isWithinTx();
    }

    static void addAfterTxCommit(Runnable runnable) {
        TxnImpl.addAfterTxCommit(runnable);
    }

    static void addAfterTxRollback(Runnable runnable) {
        TxnImpl.addAfterTxRollback(runnable);
    }

    static Txn begin() {
        return begin(TxDataSource.DEFAULT_NAME);
    }

    static Txn begin(String txnName) {
        return begin(txnName, Isolation.DEFAULT);
    }

    static Txn begin(Isolation isolation) {
        return begin(TxDataSource.DEFAULT_NAME, isolation, false);
    }

    static Txn begin(String txnName, Isolation isolation) {
        return begin(txnName, isolation, false);
    }

    static Txn begin(String txnName, boolean readonly) {
        return begin(txnName, Isolation.DEFAULT, readonly);
    }

    static Txn begin(Isolation isolation, boolean readonly) {
        return begin(TxDataSource.DEFAULT_NAME, isolation, readonly);
    }

    static Txn begin(String txnName, Isolation isolation, boolean readonly) {
        return TxnImpl.begin(txnName, isolation, readonly);
    }

    void commit() throws SQLException;

    void rollback() throws SQLException;

    void close() throws SQLException;
}
